package pers.jsan.litheopen.security.filter.authorize;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.jsan.litheopen.client.entity.LitheClient;
import pers.jsan.litheopen.client.service.ILitheClientService;
import pers.jsan.litheopen.security.exception.LitheAuthenticationException;
import pers.jsan.litheopen.security.filter.AuthenticationFilterChain;
import pers.jsan.litheopen.security.filter.LitheAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CheckClientFilter implements LitheAuthenticationFilter {

    @Autowired
    private ILitheClientService litheClientService;

    @Override
    public void doFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, AuthenticationFilterChain filterChain) throws IOException, ServletException, LitheAuthenticationException {
        String client_id = servletRequest.getParameter("client_id");
        String redirect_uri = servletRequest.getParameter("redirect_uri");
        LitheClient litheClient = litheClientService.getOne(new LambdaQueryWrapper<LitheClient>().eq(LitheClient::getClientId, client_id));
        if(null == litheClient || !litheClient.getClientRedirectUri().equals(redirect_uri)) {
            throw new LitheAuthenticationException("请求的授权类型异常");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
